<template>
    <view class="orderManage">
        <uni-nav-bar fixed left-icon="left" title="订单管理" @clickLeft="backHandle" class="unibarS">
            <block slot="right">
                <text class="sub-btn" @click="addOrder">新增订单</text>
            </block>
        </uni-nav-bar>
        <u-sticky offset-top="0">
			<dropdown-screen
				ref="dropdownScreen"
				:barFontSize="32"
				:barTextColor="'rgba(12, 16, 25, 1)'"
				:activeColor="'rgba(77, 172, 177, 1)'"
				@tabClick="tabClick"
				@confirm="confirm"
				@reset="reset"
				:listArr="listArr">
				<template v-slot:content>
					<view class="searchContent" v-show="searchType == 0">
						<u--form labelPosition="top" ref="uForm" labelWidth="70">
							<u-form-item label="排序方式" ref="item1">
								<radio-group @change="radioChangeSortKeyValues" class="radio-group-box">
									<label>
										<radio value="desc" :checked="tempSearchObj.sortKeyValues === 'desc'" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>正序排序</text>
									</label>
									<label>
										<radio value="asc" :checked="tempSearchObj.sortKeyValues === 'asc'" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>倒序排序</text>
									</label>
								</radio-group>
							</u-form-item>
							<u-form-item label="排序属性" ref="item1">
								<radio-group @change="radioChangeSortKey" class="radio-group-box">
									<label v-for="(item, index) in sortPropsList" :key="index">
										<radio :value="item.value" :checked="tempSearchObj.sortKey === item.value" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>{{ item.name }}</text>
									</label>
								</radio-group>
							</u-form-item>
						</u--form>
					</view>
					<view class="searchContent" v-show="searchType == 1">
						<u--form labelPosition="top" ref="uForm" labelWidth="100">
							<u-form-item label="付款方式" ref="item1">
								<radio-group @change="radioChange($event, 'paymentType')" class="radio-group-box">
									<label v-for="(item, index) in bus_pay_status" :key="index">
										<radio :value="item.dictValue" :checked="tempSearchObj.paymentType === item.dictValue" iconColor="#FFFFFF" activeBackgroundColor="#4DACB1" />
										<text>{{ item.dictLabel }}</text>
									</label>
								</radio-group>
							</u-form-item>
							<u-form-item label="归属人员" border ref="item1">
								<view class="flex-sub">
									<view class="flex-sub-item" v-for="item in tempSearchObj.createBy" :key="item.userId">
                                        <u-avatar
                                            :src="item.avatar" class="avatar" :size="30">
                                        </u-avatar>
                                        <view class="name">{{ item.userName }}</view>
                                    </view>
								</view>
								<u-icon  @click="selectHandle()" slot="right" name="plus-circle-fill" size="30"></u-icon>
							</u-form-item>
							<u-form-item class="search-item-box" label="创建时间"  @click="openCalendar()" border ref="item1">
								<view>
									<view v-if="tempSearchObj.startTime">{{ tempSearchObj.startTime + '-' + tempSearchObj.endTime}}</view>
									<view v-else>选择时间段</view>
								</view>
								<u-icon slot="right" name="clock"></u-icon>
							</u-form-item>
						</u--form>
					</view>
				</template>
			</dropdown-screen>
		</u-sticky>
        <view class="tab-box">
            <u-tabs :list="tabList"  @click="clickTab"></u-tabs>
        </view>
        <uni-search-bar class="uni-mt-10" v-model="params.keyword" bgColor="#FFFFFF" radius="5" placeholder="搜索" clearButton="auto"
            cancelButton="none" @confirm="searchHandle()" @clear="searchHandle()" />
        <view v-if="list.length" class="list">
            <view class="item" v-for="(item, index) in list" :key="index" @click="goOrderDetails(item)">
                <view class="item-top">
                    <view class="item-top-left">
                        <view class="name">订单编号：{{ item.orderNumber }}</view>
                    </view>
                    <view class="item-top-right">
                        <view class="state" :style="{ color: getColor(item.orderStatus) }">{{ bus_order_status[item.orderStatus] }}</view>
                    </view>
                </view>
                <view class="item_content">
                    <view class="item_content_left">
                        <view><text>客户名称: </text><text>{{ item.customerName }}</text></view>
                        <view><text>订单金额: </text><text>¥{{ item.orderTotalAmount }}</text></view>
                        <view><text>已回款金额: </text><text>¥{{ (Number(item.receivedAmount) + Number(item.depositAmount)).toFixed(2) }}</text></view>
                        <view><text>付款方式: </text><text>{{ bus_pay_Method[item.paymentMethod] }}</text></view>
                        <view><text>付款类型: </text><text>{{ bus_pay_type_list[item.paymentType] }}</text></view>
                        <view><text>订单日期: </text><text>{{ item.createTime }}</text></view>
                    </view>
                    <view class="item_content_right">
                        <view style="display: flex; flex-direction: column; align-items: center;">
                            <u-avatar :src="'/static/img/dd.png'"></u-avatar>
                            <view class="salesman">{{ item.businessManager }}</view>
                        </view>
                    </view>
                </view>
                <view class="item_bottom">
                    <view @click.stop="goShipping(item)">查看发货信息</view>
                    <template v-if="params.type == 1">
                        <view v-if="item.orderStatus == '1001' || item.orderStatus == '1007' || item.orderStatus == '1008'" @click.stop="deleteHandle(index,item)">删除</view>
                        <view @click.stop="toggleTop(item)">置顶</view>
                        <view @click.stop="goExamine(item)" v-if="item.orderStatus == '1003'">撤销审批</view>
                        <view @click.stop="editOrder(item)" v-if="item.orderStatus == '1001'">编辑</view>
                    </template>
                    <!-- <template v-if="params.type == 2">
                        <view @click.stop="endHandle(item)">结束订单</view>
                    </template> -->

                </view>
            </view>
            <uni-load-more :status="status" />
        </view>
        <empty-view v-else></empty-view>
        
        <view class="bottom-box">
            <text @click="seeMoney()">订单总金额3项合计</text>
            <u-icon name="arrow-right" color="#4DACB1" size="16"></u-icon>
        </view>
        <!-- 弹出框 -->
        <uni-popup ref="popup" type="bottom" background-color="#fff" border-radius="10px 10px 0 0">
            <view class="popup-box">
                <view class="popup-header">订单金额合计</view>
                <view class="popup-content">
                    <view>
                        <text>订单总金额</text>
                        <text class="price">¥ {{ totalAmt.orderTotalAmount }}</text>
                    </view>
                    <view>
                        <text>已回款金额</text>
                        <text class="price">¥ {{ totalAmt.realTotalAmount }}</text>
                    </view>
                    <view>
                        <text>未回款金额</text>
                        <text class="price">¥ {{ totalAmt.unRealTotalAmount }}</text>
                    </view>
                </view>
                <view class="popup-footer">
                    <button @click="closePopup" type="primary" size="20" style="width: 100%; background-color: #4DACB1;">关闭</button>
                </view>
            </view>
        </uni-popup>
        <!-- 结束订单 -->
        <uni-popup ref="popupOperation" type="bottom" background-color="#fff" border-radius="10px 10px 0 0">
            <view class="popup-box" style="padding: 32rpx;">
                <view class="popup-header">结束订单</view>
                <view class="end-content">
                    <view class="tips_end">是否结束订单，如需结束请填写结束原因：</view>
                    <textarea v-model="endForm.operationContent" maxlength="300" placeholder="请填写结束原因" style="height: 300rpx; width: 100%; background-color: #F7F8FA; padding: 24rpx; box-sizing: border-box;" />
                </view>
                <view @click="endAjax()" class="end-footer">确认结束</view>
            </view>
        </uni-popup>
            <!-- 选择跟进日期 -->
        <uni-calendar ref="calendar" class="uni-calendar--hook" :range="true" :clear-date="true" :date="info.date"
            :insert="info.insert" @confirm="confirmCalendar" @close="closeCalendar" />

    </view>
</template>

<script>
import { convertToDict } from '@/common/utils'
import dropdownScreen from '@/components/dropdown-screen/dropdown-screen'
export default {
    components: {
		dropdownScreen
	},
    data() {
        return {
            tabList: [
                { name: '全部订单', type: 1 },
                { name: '我的订单', type: 2 }
            ],
            urlStr: '/app/order/list',
            params: {
                type: 1,
				keyword: '',
                orderStatus: null,
				pageNum: 1,
				pageSize: 20,

                createBy: null,
                sortKey: 'create_time',
				sortKeyValues: 'desc',
                paymentType: null,
                receivedStatus: null,
                startTime: null,
                endTime: null
			},
            total: 0,
			status: 'loading',
            list: [],
            totalAmt: {
                orderTotalAmount: 0,
                realTotalAmount: 0,
                unRealTotalAmount: 0
            },
            // 排序0  筛选1
			searchType: 0,
            tempSearchObj: {
                createBy: null,
				sortKey: 'create_time',
				sortKeyValues: 'desc',
                paymentType: null,
                receivedStatus: null,
                startTime: null,
                endTime: null
			},
            showCalendar: true, // 显示日历
            info: {
                insert: false,
                selected: []
            },
            listArr: [
				{
					label: '排序',
					iconPath: '/static/svg/icon-paixu.svg'
				},
				{
					label: '筛选',
					iconPath: '/static/svg/icon-shaixuan.svg'
				}
			],
            sortPropsList: [
				{ name: '创建时间', value: 'create_time' }
			],
            operationContent: '',
            endForm: {
                id: null,
                operationContent: ''
            },
        }
    },
    onLoad() {
        this.bus_order_status = convertToDict(JSON.parse(uni.getStorageSync('bus_order_status')))
        this.bus_pay_status = JSON.parse(uni.getStorageSync('bus_order_status'))

        // 付款类型
        this.bus_pay_type = JSON.parse(uni.getStorageSync('bus_pay_type'))
        this.bus_pay_type_list = convertToDict(this.bus_pay_type)
        // 付款方式
        this.bus_pay = JSON.parse(uni.getStorageSync('bus_pay_status'))
        this.bus_pay_Method = convertToDict(this.bus_pay)
		this.getData()
	},
    onReachBottom() {
		console.log('上拉加载onReachBottom')
		if (this.status == 'noMore' || this.status == 'loading') return
		this.params.pageNum = this.params.pageNum + 1
		this.status = 'loading'
		this.getData()
	},
    methods: {
        getData() {
            let obj = JSON.parse(JSON.stringify(this.params))
            if(obj.createBy) {
                obj.createBy = obj.createBy.map(item => item.userId).join(',')
            }
			this.$http.get(this.urlStr, obj).then(res => {
				if (res.code == 200) {
					this.list = [...this.list, ...res.rows]
                    this.totalAmt.orderTotalAmount = res.orderTotalAmount
                    this.totalAmt.unRealTotalAmount = res.unRealTotalAmount
                    this.totalAmt.realTotalAmount = res.realTotalAmount
					this.total = res.total
					if (this.total > this.list.length) {
						console.log('有更多数据')
						this.status = 'more'
					} else {
						console.log('没更多数据')
						this.status = 'noMore'
					}
				} else {
					uni.$u.toast(res.msg)
				}
			})
		},
        clickTab(item) {
            console.log(item)
            this.params.type = item.type
            if(item.type == 1) {
                this.urlStr = '/app/order/list'
            } else if(item.type == 2) {
                this.urlStr = '/app/neworder/my/list'
            }
            this.list = []
            this.params.pageNum = 1
            this.getData()
        },
        addOrder() {
            uni.navigateTo({
                url: '/pages/order/addOrder'
            });
        },
        editOrder(item) {
            uni.navigateTo({
                url: '/pages/order/addOrder?id=' + item.orderNumber + '&type=edit'
            });
        },
        goShipping(item) {
            uni.navigateTo({
                url: '/pages/order/shippingInfo',
                success: function (res) {
                    console.log(item)
                    let arr = JSON.parse(JSON.stringify(item.yyLogisticsInformation))
                    res.eventChannel.emit('emitDataHandle', { data: arr })
                }
            });
        },
        searchHandle() {
			this.params.pageNum = 1
			this.status = 'loading'
			this.list = []
			this.getData()
		},
        seeMoney() {
            this.$refs.popup.open()
        },
        closePopup() {
            this.$refs.popup.close()
        },
        radioChange(e, props) {
			console.log(e)
			console.log(props)
			this.tempSearchObj[props] = e.detail.value
		},
		// 点击了 切换了 搜索标签
		tabClick(item) {
            Object.keys(this.params).forEach(key => {
				if (this.tempSearchObj.hasOwnProperty(key)) {
					this.tempSearchObj[key] = this.params[key];
				}
			});
			this.searchType = item.index
		},
		reset() {
			this.tempSearchObj = {
				sortKey: 'create_time',
				sortKeyValues: 'desc',
                paymentType: null,
                receivedStatus: null,
                startTime: null,
                endTime: null
			}
			Object.keys(this.tempSearchObj).forEach(key => {
				if (this.params.hasOwnProperty(key)) {
					this.params[key] = this.tempSearchObj[key];
				}
			});
			this.searchHandle()
		},
		confirm() {
			Object.keys(this.tempSearchObj).forEach(key => {
				if (this.params.hasOwnProperty(key)) {
					this.params[key] = this.tempSearchObj[key];
				}
			});
			this.searchHandle()
		},
        		// 打开日历
		openCalendar(type) {
            this.$refs.calendar.open()
        },
        // 确定日期
        confirmCalendar(e) {
			console.log(e)
            if(e.range.before && e.range.after) {
                this.tempSearchObj.startTime = e.range.before
                this.tempSearchObj.endTime = e.range.after
				// let arr = []
				// arr[0] = e.range.before? e.range.before : null
				// arr[1] = e.range.after? e.range.after : null
				// this.tempSearchObj.createTimes = arr.join('-')
				// console.log(this.tempSearchObj.createTimes)
			} else {
				this.tempSearchObj.createTimes = null
				// uni.$u.toast('请选择时间范围')
				return
			}
        },
        // 关闭日历
        closeCalendar() { },
        goOrderDetails(item) {
            uni.navigateTo({
                url: '/pages/order/orderDetails?id=' + item.orderNumber
            });
        },
        getColor(state) {
            let color;
                switch (state) {
                case '1001':
                case '1006':
                    color = 'rgba(255, 0, 28, 1)';
                    break;
                case '1002':
                    color = 'rgba(0, 186, 173, 1)';
                    break;
                case '1003':
                case '1004':
                case '1005':
                case '1009':
                    color = 'rgba(255, 141, 26, 1)';
                    break;
                case '1010':
                case '1011':
                case '1012':
                    color = 'rgba(42, 130, 228, 1)';
                    break;
                default:
                    color = 'rgba(255, 0, 28, 1)';
            }
            return color;
        },
        // 选择业务员
        selectHandle(type) {
            let that = this
            uni.navigateTo({
                url: '/pages/crm/customer/selectSalesmanMultiple',
                events: {
                    // 为指定事件添加一个监听器，获取被打开页面传送到当前页面的数据
                    someEvent: function (data) {
                        that.tempSearchObj.createBy = data.data
						console.log(data)
                    },
                },
                success: function (res) {
					let list = JSON.parse(JSON.stringify(that.tempSearchObj.createBy))
 
                    res.eventChannel.emit('emitDataHandle', { data: list, type: true })
                }
            });
        },
        // 置顶
        toggleTop(item) {
            this.$http.put('/app/neworder/my/top', { id: item.id }).then(res => {
                console.log(res)
				if (res.data.code == 200) {
                    uni.$u.toast('置顶成功!')
                    this.list = []
                    this.params.pageNum = 1
                    this.getData()
				} 
			})
        },
        deleteHandle(index,item) {
            let that = this
            uni.showModal({
                title: '删除提示',
                content: '确定要删除该订单吗？',
                success: function (res) {
                    if (res.confirm) {
                        console.log('用户点击确定');
                        that.delAjax(index,item.id)
                    } else if (res.cancel) {
                        console.log('用户点击取消');
                    }
                }
            });
        },
        delAjax(index,id) {
            this.$http.del('/app/order/' + id, { }).then(res => {
                console.log(res)
				if (res.data.code == 200) {
                    uni.$u.toast('删除成功!')
                    this.list.splice(index, 1)
				} 
			})
        },
        // 撤销审批 -  1.获取审批信息
        goExamine(item) {
			let that = this
			uni.showModal({
			    title: '删除提示',
			    content: '确定要撤销审批吗？',
			    success: function (res) {
			        if (res.confirm) {
					that.$http.get('/app/neworder/my/findProcess', { processId: item.processNumber }).then(ress => {
						console.log(ress)
						if (ress.code == 200) {
							that.examineAjax(ress.data.flowId, ress.data.processInstanceId)
						} 
					})
			        } else if (res.cancel) {
			            console.log('用户点击取消');
			        }
			    }
			});

        },
        // 撤销审批 -  2.获取审批信息
        examineAjax(flowId, processInstanceId) {
            this.$http.post('/flyflow-api/process-instance/stopProcessInstance', { flowId, processInstanceId }, false).then(res => {
                console.log(res)
				if (res.data.ok == true) {
                    uni.$u.toast('撤销成功!')
                    this.list = []
                    this.params.pageNum = 1
                    this.getData()
				} 
			})
        },
        endHandle(item) {
            this.endForm.id = item.id
            this.$refs.popupOperation.open()
        },
        endAjax() {
            this.$http.put('/app/neworder/my/end', this.endForm).then(res => {
                console.log(res)
				if (res.data.code == 200) {
                    uni.$u.toast('结束成功!')
                    this.$refs.popupOperation.close()
                    this.list = []
                    this.params.pageNum = 1
                    this.getData()
				} 
			})
        },
        backHandle() {
            uni.navigateBack()
        }
    }
}
</script>

<style lang="scss" scoped>
/deep/.u-sticky {
	z-index: 10 !important;
}
/deep/.uni-navbar__header-btns-right {
    width: 70px !important;
}

.orderManage {
    padding-bottom: 44px;
    .tab-box {
        background: #fff;
    }
}

.list {
    >view:last-child {
        margin-bottom: 0;
    }
}

.item {
    margin: 0 20rpx;
    padding: 28rpx;
    border-radius: 24rpx;
    background: rgba(255, 255, 255, 1);
    margin-bottom: 20rpx;

    .item-top {
        display: flex;
        justify-content: space-between;
        align-items: center;
        border-bottom: 1rpx solid rgba(103, 117, 133, 0.1);;
        padding-bottom: 20rpx;
        margin-bottom: 20rpx;
        // margn-bottom: 20rpx;
        .item-top-left {
            flex: 1;
            margin-right: 20rpx;
            width: 0;

            .name {
                font-size: 28rpx;
                font-weight: 400;
                color: rgba(103, 117, 133, 1);
                // 超出显示省略号
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        }

        .item-top-right {
            .state {
                font-size: 28rpx;
                font-weight: 400;
                color: rgba(0, 186, 173, 1);
            }
        }
    }
    .item_content {
        display: flex;
        align-items: center;
        .item_content_left {
            width: 0;
            flex: 1;
            >view {
                margin-bottom: 20rpx;
                font-size: 28rpx;
                // 超出显示省略号
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
                >text:nth-child(1) {
                    color: rgba(103, 117, 133, 1);
                    display: inline-block;
                    // margin-right: 20rpx;
                    width: 160rpx;
                }
                >text:nth-child(2) {
                    font-weight: 500;
                    color: rgba(12, 16, 25, 1);
                }
            }
        }
        .item_content_right {
            .salesman {
                margin-top: 8rpx;
                font-size: 32rpx;
                font-weight: 500;
                color: rgba(12, 16, 25, 1);
                // width: 100%;
                // 超出隐藏
                overflow: hidden;
                text-overflow: ellipsis;
                white-space: nowrap;
            }
        }
    }
    .item_bottom {
        display: flex;
        justify-content: flex-end;
        > view {
            border-radius: 10rpx;
            padding: 14rpx;
            font-size: 24rpx;
            font-weight: 400;
            color: rgba(12, 16, 25, 1);
            border: 2rpx solid rgba(103, 117, 133, 0.5);
            margin-left: 20rpx;
        }
    }
}

.bottom-box {
    height: 44px;
    position: fixed;
    bottom: 0;
    left: 0;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 0px 12rpx rgba(0, 0, 0, 0.1);

    text {
        font-size: 28rpx;
        font-weight: 500;
        color: rgba(77, 172, 177, 1);
    }

}

.popup-box {
    padding: 32rpx 0;

    .popup-header {
        display: flex;
        justify-content: center;
        margin-bottom: 32rpx;
    }
    .popup-content {
        padding: 0 32rpx;
        > view {
            display: flex;
            justify-content: space-between;
            margin-bottom: 32rpx;
            .price {
                color: rgba(255, 0, 28, 1);
            }
        }
    }
    .popup-footer {
        padding: 0 32rpx;
    }
}
.tips_end {
    font-size: 28rpx;
    font-weight: 400;
    color: rgba(12, 16, 25, 1);
    margin-bottom: 20rpx;
}
.end-footer {
    margin-top: 20rpx;
    height: 88rpx;
    line-height: 88rpx;
    text-align: center;
    border-radius: 12rpx;
    background: #4DACB1;
    font-size: 32rpx;
    font-weight: 500;
    color: rgba(255, 255, 255, 1);
}
</style>